//
//  BYAdminLoginView.m
//  School+
//
//  Created by Sean Sebastian on 5/15/16.
//  Copyright © 2016 Sean Sebastian. All rights reserved.
//

#import "BYAdminLoginView.h"

// frameworks
#import "Masonry.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "MJExtension.h"

// model
#import "AdminAccount.h"

// extension
#import "NSString+BYDateAndString.h"

@implementation BYAdminLoginView


- (void)prepareUI
{
    
    [self addSubview:self.backgroundImageView];
    [self addSubview:self.username];
    [self addSubview:self.password];
    [self addSubview:self.signIn];
    
    [self.backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).insets(UIEdgeInsetsMake(0,0,0,0));
    }];
    
    
    [self.username mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.left.equalTo(self).with.offset(35);
        make.right.equalTo(self).with.offset(-35);
        make.top.equalTo(self).with.offset(100);
        make.height.mas_equalTo(@46);
    }];
    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.username);
        make.height.equalTo(self.username);
        make.width.equalTo(self.username);
        make.top.equalTo(self.username.mas_bottom).with.offset(20);
    }];
    
    [self.signIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.password);
        make.height.mas_equalTo(@40);
        make.width.mas_equalTo(self.username);
        make.top.equalTo(self.password.mas_bottom).with.offset(20);
    }];
}

// override initialization method
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        
    }
    return self;
}


- (void)signInClick:(UIButton *)sender
{
    if ([self.username.text isEqualToString:@""] || [self.password.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"用户名／密码不能为空！"];
        return;
    }else{
        NSURL *url = [NSURL URLWithString:@"http://localhost/SchoolPlus/AdminLogin.php"];
        NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",self.username.text,self.password.text];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSDate *date = [NSString dateFromString:result[@"createTime"]];
            if (result[@"name"]) {
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                NSDictionary *dict = @{
                                       @"username":result[@"name"],
                                       @"password":result[@"password"],
                                       @"email":result[@"email"],
                                       @"iconImageURL":result[@"iconImageURL"],
                                       @"createTime":date,
                                       @"adminID":result[@"id"]
                                       };
                [AdminAccount mj_objectWithKeyValues:dict];
                [self.delegate loginViewLoginClick];
                
            }else{
                [SVProgressHUD showErrorWithStatus:result[@"errorMessage"]];
                return ;
            }
            
            
        }];
        
        self.username.text = @"";
        self.password.text = @"";
    }
}


- (UIButton *)signIn
{
    if (_signIn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.backgroundColor = [UIColor whiteColor];
        btn.alpha = 0.8f;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:@"登陆" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(signInClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _signIn = btn;
        
        return btn;
    }
    return _signIn;
}


- (UITextField *)username
{
    if (_username == nil) {
        UITextField *username = [[UITextField alloc] init];
        username.placeholder = @"请输入用户名\email";
        username.borderStyle = UITextBorderStyleLine;
        username.backgroundColor = [UIColor whiteColor];
        username.alpha = 0.8f;
        _username = username;
        
        return username;
    }
    return _username;
}

- (UITextField *)password
{
    if (_password == nil) {
        UITextField *password = [[UITextField alloc] init];
        password.placeholder = @"请输入密码";
        password.secureTextEntry = YES;
        password.borderStyle = UITextBorderStyleLine;
        password.backgroundColor = [UIColor whiteColor];
        password.alpha = 0.8f;
        _password = password;
        
        return password;
    }
    
    return _password;
}
- (UIImageView *)backgroundImageView
{
    if (_backgroundImageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"adminLogin"]];
        _backgroundImageView = imageView;
        return imageView;
    }
    return _backgroundImageView;
}


@end
